//
//  DBHistoryDataSr03.m
//  CareRingApp
//
//  Created by Linktop on 2022/8/15.
//

#import "DBHistoryDataSr03.h"
#import "HMDBManager.h"
#import "LTSRingSDK.h"
#import "TimeUtils.h"
#import "DBHeartRate.h"
#import "SRHistoryDataSR03+OtherCalc.h"
#import "DBSleepData.h"
#import "Tools.h"

NSString * const TABLE_NM_HISDATA_SR03 = @"table_his_data_sr03";


@implementation DBHistoryDataSr03

#pragma mark --数据库相关
//创建数据库
+(void)createTable
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        //创建数据库表
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(time INTEGER, macAdres TEXT NOT NULL, dataUuid INT, isWear BOOLEAN, soprtTimes INT, steps INT, skinTemp FLOAT, bloodOxygen FLOAT, hrv FLOAT, deviceModifyHeartRate INT, heart_ori_1 INT, heart_ori_2 INT, heart_ori_3 INT, measureType INT, br INT, isSportMode BOOLEAN, devFixStep BOOLEAN, battery INT, PRIMARY KEY(time, macAdres))", TABLE_NM_HISDATA_SR03];
        bool succ = [db executeUpdate:sql];
        NSLog(@"create table %@ result =%d ", TABLE_NM_HISDATA_SR03, succ);
        
        BOOL hasbr = NO;
        FMResultSet *rs = [db executeQuery:@"select * from sqlite_master where name = ? and sql like ?", TABLE_NM_HISDATA_SR03, @"br"]; // from V1.2.0 2023-5-17
        while ([rs next]) {
            hasbr = YES;
            break;
        }
        [rs close];
        
        if (hasbr == NO) {
            // 更新表
            NSString *alertString = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN br INT",TABLE_NM_HISDATA_SR03];
            BOOL succ = [db executeUpdate:alertString];
            NSLog(@"TABLE_NM_HISDATA_SR03 改表 %d", succ);
        }
        
        // isSportMode
        BOOL hasspMode = NO;
        FMResultSet *rsSpmode = [db executeQuery:@"select * from sqlite_master where name = ? and sql like ?", TABLE_NM_HISDATA_SR03, @"isSportMode"]; // from 2023-7-19
        while ([rsSpmode next]) {
            hasspMode = YES;
            break;
        }
        [rsSpmode close];
        
        if (hasspMode == NO) {
            // 更新表
            NSString *alertString = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN isSportMode BOOLEAN,  ADD COLUMN devFixStep BOOLEAN",TABLE_NM_HISDATA_SR03];
            BOOL succ = [db executeUpdate:alertString];
            NSLog(@"TABLE_NM_HISDATA_SR03 改表 +isSportMode + devFixStep %d", succ);
        }
        // battery
        BOOL hasBattery = NO;
        FMResultSet *rsBattery = [db executeQuery:@"select * from sqlite_master where name = ? and sql like ?", TABLE_NM_HISDATA_SR03, @"battery"]; // from 2023-7-19
        while ([rsBattery next]) {
            hasBattery = YES;
            break;
        }
        [rsBattery close];
        
        if (hasBattery == NO) {
            // 更新表
            NSString *alertString = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN battery INT",TABLE_NM_HISDATA_SR03];
            BOOL succ = [db executeUpdate:alertString];
            NSLog(@"TABLE_NM_HISDATA_SR03 改表 +battery + devFixStep %d", succ);
        }
        
    }];
    
}
//+(void)createTable
//{
//
//    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        //创建数据库表
//        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(time DOUBLE, macAdres TEXT NOT NULL, dataUuid INT, isWear BOOLEAN, soprtTimes INT, steps INT, skinTemp FLOAT, bloodOxygen FLOAT, hrv FLOAT, deviceModifyHeartRate INT, heart_ori_1 INT, heart_ori_2 INT, heart_ori_3 INT, measureType INT)", TABLE_NM_HISDATA_SR03];
//        bool succ = [db executeUpdate:sql];
//        NSLog(@"create table %@ result =%d ", TABLE_NM_HISDATA_SR03, succ);
//
//    }];
//
//}

+(void)queryBy:(NSString * _Nonnull)macAdres Begin:(NSDate *)beginDate End:(NSDate *)endDate OrderBeTimeDesc:(BOOL)isDesc Cpmplete:(void(^)(NSMutableArray<DBHistoryDataSr03 *> *results))cmpBlk
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {

        NSMutableArray<DBHistoryDataSr03 *> *results = [NSMutableArray new];
        NSString *sql =  [NSString stringWithFormat:@"SELECT rowid , * FROM %@ WHERE macAdres = ? AND (time >= ? AND time < ?) ORDER BY time %@", TABLE_NM_HISDATA_SR03, isDesc ? @"DESC" : @"ASC"];
        FMResultSet *rs = [db executeQuery:sql, macAdres, beginDate, endDate];
        while ([rs next]) {
            DBHistoryDataSr03 *historyModel = [[DBHistoryDataSr03 alloc]init];
          
            historyModel.cId = [rs intForColumn:@"rowid"];
            historyModel.time = @([rs doubleForColumn:@"time"]);
            historyModel.dataUuid = @([rs intForColumn:@"dataUuid"]);
            historyModel.isWear = @([rs boolForColumn:@"isWear"]);
            historyModel.soprtTimes = @([rs intForColumn:@"soprtTimes"]);
            historyModel.steps = @([rs intForColumn:@"steps"]);
            historyModel.skinTemp = @([rs doubleForColumn:@"skinTemp"]);
            historyModel.bloodOxygen = @([rs intForColumn:@"bloodOxygen"]);
            historyModel.deviceModifyHeartRate = @([rs intForColumn:@"deviceModifyHeartRate"]);
            historyModel.heart_ori_1 = @([rs intForColumn:@"heart_ori_1"]);
            historyModel.heart_ori_2 = @([rs intForColumn:@"heart_ori_2"]);
            historyModel.heart_ori_3 = @([rs intForColumn:@"heart_ori_3"]);
            historyModel.measureType = [rs intForColumn:@"measureType"];
            historyModel.macAddress = [rs stringForColumn:@"macAdres"];
            historyModel.hrv = @([rs doubleForColumn:@"hrv"]);
            historyModel.isSportMode = [rs boolForColumn:@"isSportMode"];
            
            if(![rs columnIsNull:@"br"]) {
                historyModel.respiratory = @([rs intForColumn:@"br"]);
            }
            
            [results addObject:historyModel];
            
        }
        [rs close];
       
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(results);
            });
        }
       
    }];
}


+(void)queryForSleepCalcBy:(NSString * _Nonnull)account Begin:(NSDate *)beginDate End:(NSDate *)endDate OrderBeTimeDesc:(BOOL)isDesc NeedCalcRestHr:(BOOL)needCalcRestHr Cpmplete:(void(^)(NSMutableArray<NSMutableDictionary *> *results, NSMutableArray<DBHistoryDataSr03 *> *objArray))cmpBlk
{
    
    
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {

        NSMutableArray<NSMutableDictionary *> *results = [NSMutableArray new];
        NSMutableArray<DBHistoryDataSr03 *> *objArray = [NSMutableArray new];
        NSString *sql =  [NSString stringWithFormat:@"SELECT rowid , * FROM %@ WHERE macAdres = ? AND (time >= ? AND time < ?)  ORDER BY time %@", TABLE_NM_HISDATA_SR03, isDesc ? @"DESC" : @"ASC"];
        FMResultSet *rs = [db executeQuery:sql, account, beginDate, endDate];
    
        while ([rs next]) {
            NSMutableDictionary *mutDict = [[NSMutableDictionary alloc]init];

            mutDict.first = @([rs doubleForColumn:@"time"]);

            mutDict.third = @([rs intForColumn:@"soprtTimes"]);

            mutDict.second = @([rs intForColumn:@"deviceModifyHeartRate"]);

            [results addObject:mutDict];
            
            // 原始
            DBHistoryDataSr03 *historyModel = [[DBHistoryDataSr03 alloc]init];

            historyModel.time = @([rs doubleForColumn:@"time"]);
            historyModel.dataUuid = @([rs intForColumn:@"dataUuid"]);
            historyModel.isWear = @([rs boolForColumn:@"isWear"]);
            historyModel.soprtTimes = @([rs intForColumn:@"soprtTimes"]);
            historyModel.steps = @([rs intForColumn:@"steps"]);
            historyModel.skinTemp = @([rs doubleForColumn:@"skinTemp"]);
            historyModel.bloodOxygen = @([rs intForColumn:@"bloodOxygen"]);
            historyModel.deviceModifyHeartRate = @([rs intForColumn:@"deviceModifyHeartRate"]);
            historyModel.hrv = @([rs intForColumn:@"hrv"]);
            historyModel.heart_ori_1 = @([rs intForColumn:@"heart_ori_1"]);
            historyModel.heart_ori_2 = @([rs intForColumn:@"heart_ori_2"]);
            historyModel.heart_ori_3 = @([rs intForColumn:@"heart_ori_3"]);
            historyModel.measureType = [rs intForColumn:@"measureType"];
            historyModel.devFixStep = [rs boolForColumn:@"devFixStep"];
            if (![rs columnIsNull:@"battery"]) {
                historyModel.battery = @([rs intForColumn:@"battery"]);
            }
            
            [objArray addObject:historyModel];
        }
        
        [rs close];
        
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(results, objArray);
            });
        }
       
    }];
}


// 计算静息
+(NSNumber * _Nullable)calcRestingHr:(NSArray<NSDictionary *> * )results EndTimeInterval:(NSTimeInterval)rhrEndInterval
{
    NSNumber * resHr = nil;
    __block double all = 0;
    double average_1 = 0;
    if (results.count) {
        [results enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"time"] doubleValue] <= rhrEndInterval) {
                all += [obj.second doubleValue];
            }
        }];
        average_1 = all / results.count;  // 取第一次平均值
        // 上下去除 20%
        double high = average_1 * (1.f + 0.2);
        double low = average_1 * (1.f - 0.2);
        __block double all_2 = 0;
        __block int count = 0;
        [results enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.second doubleValue] > low && [obj.second doubleValue] < high && [obj[@"time"] doubleValue] <= rhrEndInterval) {
                all_2 += [obj.second doubleValue];
                count++;
            }
            
        }];
        
       resHr = @(all_2 / count);
      
    }
    return resHr;
}

+(void)debugInsert:(NSString * _Nonnull)macAdres Array:(NSArray <NSDictionary *> *)resArray       Cpmplete:(void(^)( BOOL isSucc))cmpBlk 
{
    
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF

        BOOL allSucc = YES;
        [db beginTransaction];
        for (int i = 0; i < resArray.count; i++) {
            
            NSString *sqlString = [NSString stringWithFormat:  @"INSERT OR IGNORE INTO %@ (time , macAdres, dataUuid, isWear, soprtTimes, steps, skinTemp, bloodOxygen, hrv, deviceModifyHeartRate, heart_ori_1, heart_ori_2, heart_ori_3, measureType, br, isSportMode, devFixStep, battery) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", TABLE_NM_HISDATA_SR03];
//            if (!dataObj.hrv) {
//                dataObj.hrv = [dataObj calcHRv];
//            }
            NSDictionary *dict = resArray[i];
            BOOL succ = [db executeUpdate:sqlString,
                         dict[@"time"],
                         macAdres,
                         dict[@"dataUuid"],
                         dict[@"isWear"],
                         dict[@"soprtTimes"],
                         dict[@"steps"],
                         dict[@"skinTemp"],
                         dict[@"bloodOxygen"],
                         dict[@"hrv"], /* hrv */
                         dict[@"deviceModifyHeartRate"],
                         dict[@"heart_ori_1"],
                         dict[@"heart_ori_2"],
                         dict[@"heart_ori_3"],
                         dict[@"measureType"],
                         dict[@"br"],
                         dict[@"isSportMode"],
                         @(YES),
                         nil
                        ];
            
            allSucc = allSucc && succ;
        }
        
        
        [db commit];
        
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk( allSucc);
            });
        }
        
    }];
}


+(void)mutiInsert:(NSString * _Nonnull)macAdres Array:(NSArray <SRHistoryDataSR03 *> *)dataArray       Cpmplete:(void(^)(NSMutableArray<SRHistoryDataSR03 *> *dataArray, BOOL isSucc))cmpBlk {
    
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
        // 查询时间最大值
        NSNumber *maxTime = @(0);
        NSString *sql =  [NSString stringWithFormat:@"SELECT MAX(time) as maxTime FROM %@ WHERE macAdres = ?", TABLE_NM_HISDATA_SR03];
        FMResultSet *rs = [db executeQuery:sql, macAdres];
        while ([rs next]) {
            maxTime = @([rs doubleForColumn:@"maxTime"]);
        }
        [rs close];
        
        [db beginTransaction];
        BOOL allSucc = YES;
        NSMutableArray<SRHistoryDataSR03 *> *resArray = [NSMutableArray new];
        for (int i = 0; i < dataArray.count; i++) {
            
            SRHistoryDataSR03 *dataObj = dataArray[i];
            if (dataObj.timeStamp.doubleValue < maxTime.doubleValue) {
                // 已保存过
                continue;
            }
            if (dataObj.dataUuid.unsignedIntValue == DATA_INVALID_UUID) {
                // 无效数据
                continue;
            }
            
            if (!dataObj.isWear.boolValue) {
                // 未佩戴数据
                continue;
            }
            if (dataObj.isCharging) {
                // 充电中数据不存
                continue;
            }
            
            if (dataObj.deviceModifyHeartRate.intValue < 40)// 24-11-18 为45, 日本客户要求40以上心率
            {
                // 过滤运动模式中0心率
                continue;
            }
            if (dataObj.skinTemp.intValue >= 45)
            {
                // 误判为佩戴的数据
                continue;
            }
//            if (i > 0) {
//                if (dataObj.timeStamp.doubleValue - dataArray[i - 1].timeStamp.doubleValue < 5) {
//                    continue; // 去重
//                }
//            }
            
            [resArray addObject:dataObj];
            
            NSString *sqlString = [NSString stringWithFormat:  @"INSERT OR IGNORE INTO %@ (time , macAdres, dataUuid, isWear, soprtTimes, steps, skinTemp, bloodOxygen, hrv, deviceModifyHeartRate, heart_ori_1, heart_ori_2, heart_ori_3, measureType, br, isSportMode, devFixStep, battery) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", TABLE_NM_HISDATA_SR03];
            if (!dataObj.hrv) {
                dataObj.hrv = [dataObj calcHRv];
            }
            
            NSNumber * bloodOxygen = dataObj.bloodOxygen;
            
            if (dataObj.bloodOxygen
                && (dataObj.bloodOxygen.intValue > 50 && dataObj.bloodOxygen.intValue < 94))
            {
                bloodOxygen =  @([Tools getRandomNumber:95 to:99]);// 2024-6-25 廖贤昭邮件通知修改
            }
            
            BOOL succ = [db executeUpdate:sqlString,
                         dataObj.timeStamp,
                         macAdres,
                         dataObj.dataUuid,
                         dataObj.isWear,
                         dataObj.soprtTimes,
                         dataObj.steps,
                         dataObj.skinTemp,
                         bloodOxygen,
                         dataObj.hrv, /* hrv */
                         dataObj.deviceModifyHeartRate,
                         dataObj.heart_ori_1,
                         dataObj.heart_ori_2,
                         dataObj.heart_ori_3,
                         @(dataObj.measureType),
                         dataObj.breathRate,
                         dataObj.isSportMode,
                         @(dataObj.lis2ds12),
                         dataObj.battery
                        ];
            
            allSucc = allSucc && succ;
        }
        
        
        [db commit];
        
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(resArray, allSucc);
            });
        }
        
    }];
}

+(void)deleteFromTime:(NSTimeInterval)time macAdres:(NSString *)macAdres Cpmplete:(void(^)( BOOL isSucc))cmpBlk
{
    
    // 1660891693 - 12 * 3600
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
        [db beginTransaction];
        
        NSString *sql =  [NSString stringWithFormat:@"DELETE FROM %@ WHERE time >  ? AND macAdres = ?", TABLE_NM_HISDATA_SR03];
        BOOL succ = [db executeUpdate:sql, @(time), macAdres];
        [db commit];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk(succ);
            }
        });
       
    }];
}

+(NSNumber *)querySyncminTimeBymacAdres:(NSString *)macAdres Db:(FMDatabase * _Nonnull)db
{
    NSString *sql =  [NSString stringWithFormat:@"SELECT MIN(time) as minTime FROM %@ WHERE macAdres = ?", TABLE_NM_HISDATA_SR03];
    FMResultSet *rs = [db executeQuery:sql, macAdres, @(YES)];
    NSNumber *minTimeInterval = nil;
    while ([rs next]) {
        minTimeInterval = @([rs doubleForColumn:@"minTime"]);
    }
    
    [rs close];
    return minTimeInterval;
    
}
+(void)queryueryRestHrBymacAdres:(NSString *)macAdres Date:(NSDate *)date  CMP:(void(^)(NSNumber *restHr ))cmpBlk
{
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSNumber *restHr = @(70);
        
        NSDate *beginDate = [TimeUtils zeroOfDate:date];
        NSDate *endDate = [beginDate dateByAddingTimeInterval:24*3600 -1];
        
        NSString *sql =  [NSString stringWithFormat:@"SELECT COUNT(macAdres) as cntAcc, AVG(deviceModifyHeartRate) as avgHr FROM %@ WHERE macAdres = ? AND  time BETWEEN ? AND ? AND  deviceModifyHeartRate > ?", TABLE_NM_HISDATA_SR03];
        FMResultSet *rs = [db executeQuery:sql, macAdres, beginDate, endDate, @(LTSRingSDK.instance.heartrateFilterLowerLimit)];
        
        double average_1 = 0;
        
        while ([rs next]) {
            int count = [rs intForColumn:@"cntAcc"];
            if (count) {
                average_1 = [rs doubleForColumn:@"avgHr"];
            } else {
                restHr = nil;
            }
            
        }
        
        [rs close];
        
        // 上下去除 20%
        if (average_1 > 30) {
            double high = average_1 * (1.f + 0.2);
            double low = average_1 * (1.f - 0.2);
            
            NSString *sql2 =  [NSString stringWithFormat:@"SELECT COUNT(macAdres) as cntAcc, AVG(deviceModifyHeartRate) as avgHr FROM %@ WHERE macAdres = ? AND  time BETWEEN ? AND ?  AND deviceModifyHeartRate BETWEEN ? AND ?", TABLE_NM_HISDATA_SR03];
//            DebugNSLog(@"begintime : %lf   %lf", [beginDate timeIntervalSince1970], [endDate timeIntervalSince1970]);
            FMResultSet *rs2 = [db executeQuery:sql2, macAdres, beginDate, endDate, @(low), @(high)];
            while ([rs2 next]) {
                int count = [rs2 intForColumn:@"cntAcc"];
                if (count) {
                    restHr = @([rs2 doubleForColumn:@"avgHr"]);
                    
                    //                DebugNSLog(@"静息 %@ 第一平均 %lf 上下限(%lf, %lf) 日期 %@ 时间戳 %lf", restHr,average_1, low, high ,beginDate, [beginDate timeIntervalSince1970]);
                    
                }
                
            }
            
            [rs2 close];
        }
        
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(restHr);
            });
        }
        
    }];
    
}

+(void)queryueryRestHrBySleepObj:(DBSleepData *)sleepObj CMP:(void(^)(NSNumber *restHr ))cmpBlk
{
    NSNumber *restHr = nil;
    if (!sleepObj) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk(restHr);
            }
        });
        return;
    }
    restHr = sleepObj.hr;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (cmpBlk) {
            cmpBlk(restHr);
        }
    });
   
    
}

// 查询电量列表
+(void)queryBatteryList:(NSString * _Nonnull)macAdres Begin:(NSDate *)beginDate End:(NSDate *)endDate OrderBeTimeDesc:(BOOL)isDesc Cpmplete:(void(^)(NSMutableArray<NSDictionary *> *results))cmpBlk
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {

        NSMutableArray<NSDictionary *> *results = [NSMutableArray new];
        NSString *sql =  [NSString stringWithFormat:@"SELECT time, macAdres, battery FROM %@ WHERE macAdres = ? AND (time >= ? AND time < ?) AND (battery IS NOT NULL) ORDER BY time %@", TABLE_NM_HISDATA_SR03, isDesc ? @"DESC" : @"ASC"];
        FMResultSet *rs = [db executeQuery:sql, macAdres, beginDate, endDate];
        while ([rs next]) {
          
            NSMutableDictionary *dict = [NSMutableDictionary new];
            if (![rs columnIsNull:@"time"]) {
                NSInteger time = [rs longLongIntForColumn:@"time"];
                dict[@"time"] = @(time);
            }
            if (![rs columnIsNull:@"macAdres"]) {
                NSString * macAddress = [rs stringForColumn:@"macAdres"];
                dict[@"macAddress"] = macAddress;

            }
            
            if (![rs columnIsNull:@"battery"]) {
                
                int battery = [rs intForColumn:@"battery"];
                if (battery <= 100 && battery > 0) {
                    dict[@"battery"] = @(battery);
                }

            }
        
            if (dict.count >= 3) {
                
                [results addObject:dict];
            }
            
        }
        [rs close];
       
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(results);
            });
        }
       
    }];
}


+(void)dropTable {
#if DEBUG
 
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        //创建数据库表
        NSString   * sql = [NSString stringWithFormat:@"DROP TABLE %@", TABLE_NM_HISDATA_SR03];
        
        bool succ = [db executeUpdate:sql];
        NSLog(@"drop table %@ result =%d ", TABLE_NM_HISDATA_SR03, succ);
        
    }];
    
#endif
    
}

+(void)clearColumnBy:(NSString *)macAddress DB:(FMDatabase * _Nonnull )db
{

    NSString *sql =  [NSString stringWithFormat:@"DELETE FROM %@ WHERE  macAddress = ?", TABLE_NM_HISDATA_SR03];
    BOOL succ = [db executeUpdate:sql, macAddress];
        

}

+(void)queryForSportBy:(NSString * _Nonnull)macAddress Begin:(NSDate *)beginDate End:(NSDate *)endDate OrderBeTimeDesc:(BOOL)isDesc Cpmplete:(void(^)(NSMutableArray<NSDictionary *> *results))cmpBlk
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {

        NSMutableArray<NSDictionary *> *results = [NSMutableArray new];
        NSString *sql =  [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE macAdres = ? AND time BETWEEN ? AND ? AND isSportMode = 1 ORDER BY time %@", TABLE_NM_HISDATA_SR03, isDesc ? @"DESC" : @"ASC"];
        FMResultSet *rs = [db executeQuery:sql, macAddress, beginDate, endDate];
        while ([rs next]) {
            
            NSNumber *time = @([rs doubleForColumn:@"time"]);
            NSNumber *value = @([rs doubleForColumn:@"deviceModifyHeartRate"]);
            NSNumber *step = @([rs intForColumn:@"steps"]);
            NSDictionary *dict = @{@"time" : time,
                                   @"value" : value,
                                   @"step" : step,
            };
            
            if (value.intValue >= 70 && value.intValue <= 182) {
                
                [results addObject:dict];
            }
            
        }
        [rs close];
       
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(results);
            });
        }
       
    }];
}


@end
